//
//  SayViewController.m
//  Liuhe
//
//  Created by zr on 2018/8/7.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "SayViewController.h"

@interface SayViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UILabel * titleLabel;
@property (nonatomic, strong)UITextField * titleText;
@property (nonatomic, strong)UITextField * adressText;
@property (nonatomic, strong)UITextField * dateText;
@property (nonatomic, weak)UITextView * textView;
@property (nonatomic, weak)UIButton * addButton;
@property (nonatomic, weak)UIButton * sureButton;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, copy)NSString * images;

@end

@implementation SayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WHITE_COLOR;
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupNav{
    
    self.title = @"爆料";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0, 0, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
}

- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setupUI{
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.textColor = MAINCOLOR;
    titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    titleLabel.text = @"您好，请完善以下信息";
    
    self.titleLabel = titleLabel;
    
    [self.view addSubview:self.titleLabel];
    
    
    self.titleText = [self setupTextFiledWith:@"请输入爆料标题"];
    [self.view addSubview:self.titleText];
    
    self.adressText = [self setupTextFiledWith:@"爆料地点（选填）"];
    [self.view addSubview:self.adressText];
    
    NSString * date = [self getCurrentTimes];
    self.dateText = [self setupTextFiledWith:date];
    self.dateText.text = date;
    [self.view addSubview:self.dateText];
    
    
    // 创建textView
    UITextView *textView =[[UITextView alloc]init];
    textView.backgroundColor= WHITE_COLOR;
    textView.text = @"请输入内容（500字以内）";
    textView.font = [UIFont systemFontOfSize:14 * SCREENH6];
    textView.textColor = ColorWithRGB(0xbebebe);
    textView.delegate = self;
    textView.layer.borderColor = [ColorWithRGB(0xbebebe) CGColor];
    textView.layer.borderWidth = 1.0f;
    
    self.textView = textView;
    [self.view addSubview:self.textView];
    
    UIButton * addButton = [UIButton new];
    
    [addButton setImage:ImageNamed(@"tianjia") forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(clickAddButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.addButton = addButton;
    
    [self.view addSubview:self.addButton];
    
    
    UIButton * sureButton = [UIButton new];
    
    [sureButton setTitle:@"确认提交" forState:UIControlStateNormal];
    [sureButton setTitleColor:WHITE_COLOR forState:UIControlStateNormal];
    sureButton.titleLabel.font = [UIFont systemFontOfSize:17 * SCREENH6];
    [sureButton setBackgroundColor:MAINCOLOR];
    [sureButton addTarget:self action:@selector(clickSureButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.sureButton = sureButton;
    
    [self.view addSubview:self.sureButton];
}

- (void)viewDidLayoutSubviews{
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(20 * SCREENH6);
    }];
    
    [self.titleText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(50 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-50 * SCREENH6);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(40 * SCREENH6);
        make.height.mas_equalTo(40 * SCREENH6);
    }];
    
    [self.adressText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.titleText);
        make.top.mas_equalTo(self.titleText.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.dateText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.adressText);
        make.top.mas_equalTo(self.adressText.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.dateText);
        make.top.mas_equalTo(self.dateText.mas_bottom).offset(10 * SCREENH6);
        make.height.mas_equalTo(104 * SCREENH6);
    }];
    
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.textView);
        make.top.mas_equalTo(self.textView.mas_bottom).offset(10 * SCREENH6);
        make.width.height.mas_equalTo(52 * SCREENH6);
    }];
    
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.addButton.mas_bottom).offset(20 * SCREENH6);
        make.height.mas_equalTo(40 * SCREENH6);
        make.width.mas_equalTo(250 * SCREENH6);
    }];
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{

    [self.addButton setImage:image forState:UIControlStateNormal];
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    
    NSString * token = DEF_GET_OBJECT(@"token");

    NSDictionary * dic = @{@"files":frontImageData,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/noteupload" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat  = @"yyyyMMddHHmmss";
        NSString *str  = [formatter stringFromDate:[NSDate date]];
        NSString *fileName  = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:frontImageData name:@"files" fileName:fileName mimeType:@"image/png"];
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"===%@",responseObject);
        
        NSInteger code = [responseObject[@"status"] integerValue];
        
        if (code == 200){
            
            self.images = [NSString stringWithFormat:@"%@",responseObject[@"data"]];
        }else{
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



- (UITextField *)setupTextFiledWith:(NSString *)string{
    
    UITextField * textFiled = [[UITextField alloc] init];
    
    textFiled.borderStyle = UITextBorderStyleNone;
    textFiled.backgroundColor = [UIColor whiteColor];
    //设置光标颜色
    textFiled.tintColor = [UIColor blackColor];
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor lightGrayColor];
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:string attributes:attrs];
    textFiled.textColor = [UIColor blackColor];
    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
//    textFiled.secureTextEntry = YES;
    
    
    return textFiled;
}

- (void)clickAddButton{
    
    [self presentViewController:self.alertVC animated:YES completion:nil];
}


- (void)clickSureButton{
    
    SHOWHUD;
    
    NSString * token = DEF_GET_OBJECT(@"token");
    
    NSDictionary * dict = @{@"token":token,@"content":self.textView.text,@"title":self.titleText.text,@"date":self.dateText.text,@"adress":self.adressText.text,@"images":self.images};
    
    [[NetworkTool sharedTools] POST:@"/index/Liuheonline/burst" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        HIDDENHUD;
        NSLog(@"===%@",responseObject);
        
        NSInteger code = [responseObject[@"status"] integerValue];
        
        if (code == 200) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"恭喜你，爆料成功！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"msg"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        HIDDENHUD;
        
        NSLog(@"===%@",error);
    }];
}


- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    if(textView.text.length < 1){
        textView.text = @"请输入内容（500字以内）";
        textView.textColor = ColorWithRGB(0xbebebe);
    }else{
        
        [textView resignFirstResponder];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"请输入内容（500字以内）"]){
        textView.text=@"";
        textView.textColor=[UIColor blackColor];
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.textView resignFirstResponder];
    //    [self.textView endEditing:YES];
}


- (NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
//    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
